package handler

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

type CheckDataAgent struct {
	Type    string
	IP      []string
	TimeOut int
}

type JsonData struct {
	Code int
	Data string
}

func PostData(d CheckDataAgent, url string) (string, error) {

	b, _ := json.Marshal(d)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
	if err != nil {
		log.Printf("ERROR: Create HTTP POST request failed %s.", url)
		return "", fmt.Errorf("ERROR: Create HTTP POST request failed %s.", url)
	} else {
		log.Printf("INFO: POST target %s success.", url)
	}

	defer req.Body.Close()                                           // 必须设定该参数,POST参数才能正常提交
	req.Header.Set("Content-Type", "application/json;charset=UTF-8") // 请求头，意思是以json串提交数据

	// 响应
	response, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Printf("ERROR: Send HTTP POST request failed %s.", url)
		return "", fmt.Errorf("ERROR: Send HTTP POST request failed %s.", url)
	}

	body, err := io.ReadAll(response.Body)

	var resData JsonData
	err = json.Unmarshal(body, &resData)
	if err != nil {
		return "", fmt.Errorf("Error reading response body: %v", err)
	}

	return resData.Data, nil
}
